package forum.service.rpc;

import com.alibaba.druid.util.StringUtils;
import com.foreveross.springboot.dubbo.utils.Payload;
import forum.domain.Role;
import forum.domain.User;
import forum.domain.UserRole;
import forum.repository.RoleRepository;
import forum.repository.UserRepository;
import forum.repository.UserRoleRepository;
import forum.service.rpc.api.UserRoleService;
import forum.service.tools.BaseSearch;
import forum.service.tools.SearchDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import java.util.*;

import static com.squareup.okhttp.internal.Internal.logger;

/**
 * Created by Administrator on 2017/4/5.
 */
@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRoleRepository userRoleRepository;

    Map<String,String> error = new HashMap<String, String>();

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    public Object getUserRoleListByUsername(String username) {
        List<UserRole> list = new ArrayList();
        list = userRoleRepository.findByUsername(username);
        return list;
    }

//    @Override
    public Object getUserRoleList(@QueryParam("page") @DefaultValue("0") int page,
                              @QueryParam("size") @DefaultValue("50") int size,
                              @QueryParam("sort") @DefaultValue("sort=user_role_id,desc") String sort,
                              @QueryParam("operation") @DefaultValue("operation=eq") String operation,
                              @QueryParam("key") @DefaultValue("key=user_role_id") String key,
                              @QueryParam("value") @DefaultValue("1") String value) {
//        logger.debug("get roles: {} . -> {}", "GET /api/v1/roles/", sort);

        // 简单适配, 暂无严谨性
        sort = sort.replaceAll("sort=", "").trim(); // sort=firstname,desc
        String[] sort_arr = sort.split(",");
        Sort.Direction direction;
        if (sort_arr[1] != null && "desc".equals(sort_arr[1])) {
            direction = Sort.Direction.DESC;
        } else {
            direction = Sort.Direction.ASC;
        }
        String[] properties = sort_arr[0].split("&");

        Sort _sort = new Sort(direction, Arrays.asList(properties));
        Pageable pageable = new PageRequest(page, size, _sort);

        if(StringUtils.isEmpty(key) || StringUtils.isEmpty(operation)  || StringUtils.isEmpty(value)){
            logger.info("提示: key或者operation或者value为空 ");

        }

        if(!StringUtils.isEmpty(key) && !StringUtils.isEmpty(operation)  && !StringUtils.isEmpty(value)){
            logger.info("提示: key并且operation并且value都不为空 ");
            return userRoleRepository.findAll(new BaseSearch<UserRole>(new SearchDto(key,operation, value)),pageable);
        }

        return  userRoleRepository.findAll(pageable);

    }




//    @ResponseBody
    public Object updateUserRoleByUsername(@QueryParam("username") @DefaultValue("username=eq") String username,
                                           @RequestBody Map<String, Integer> jsonObj) {
//        List<UserRole> l = new ArrayList();

        System.out.println("总共获取到："+jsonObj.size()+"个参数");
        for(String key : jsonObj.keySet()){
            System.out.println(key + " : " + jsonObj.get(key));
        }

       List<UserRole> userRoleList =  userRoleRepository.findByUsername(username);

        if (userRoleList!=null && userRoleList.size()>0){
            Integer l =userRoleList.get(0).getUserroleid();
//        logger.info(list.get(0).toString());
            UserRole list = userRoleRepository.findOne(l);
//        l=null;
            if(list == null){
                logger.info("url出错");
                error.put("msg","没找到这个id或者url出错");
                return new Payload(error);
            }
            if (jsonObj.get("roleid") != null) {
                list.setRoleid(jsonObj.get("roleid"));
                Role role = (Role) roleRepository.findOne(jsonObj.get("roleid"));
                list.setRole(role);
            }
            if (jsonObj.get("userid") != null) {
                list.setUserid(jsonObj.get("userid") );
                User user = (User)userRepository.findOne(jsonObj.get("userid") );
                list.setUser(user);
            }
            userRoleRepository.save(list);

            logger.info(list.toString());

            return list;
        }else{

            UserRole list = new UserRole();
            if (jsonObj.get("roleid") != null) {
                list.setRoleid(jsonObj.get("roleid"));
                Role role = (Role) roleRepository.findOne(jsonObj.get("roleid"));
                list.setRole(role);
            }else {
                logger.info("roleid出错");
                error.put("msg","没roleid");
                return new Payload(error);
            }
            if (jsonObj.get("userid") != null) {
                list.setUserid(jsonObj.get("userid") );
                User user = (User)userRepository.findOne(jsonObj.get("userid") );
                list.setUser(user);
            }else {
                logger.info("userid出错");
                error.put("msg","没userid");
                return new Payload(error);
            }
            userRoleRepository.save(list);

            logger.info(list.toString());

            return list;
        }

    }

    public Object createUserRoleByUsername(@QueryParam("username") @DefaultValue("username=eq") String username,
                                           @RequestBody Map<String, Integer> jsonObj) {

        System.out.println("总共获取到："+jsonObj.size()+"个参数");
        for(String key : jsonObj.keySet()){
            System.out.println(key + " : " + jsonObj.get(key));
        }
        UserRole list = new UserRole() ;
        if (jsonObj.get("roleid") != null) {
            list.setRoleid(jsonObj.get("roleid"));
            Role role = (Role) roleRepository.findOne(jsonObj.get("roleid"));
            if (role==null){
                return "role不存在";
            }
            list.setRole(role);
        }
        if (jsonObj.get("userid") != null) {
            list.setUserid(jsonObj.get("userid") );
            User user = (User)userRepository.findOne(jsonObj.get("userid") );
            if (user==null){
                return "user不存在";
            }
            list.setUser(user);
        }

        userRoleRepository.save(list);

        return list;
    }




}
